<script setup lang="ts">
import { Delete, Refresh, VideoPause, VideoPlay } from "@element-plus/icons-vue";
import Aewave from '@/views/components/aewave/aewave.vue';
import { onMounted, onUnmounted, reactive, ref, toRaw, watch, computed } from "vue";
import {
  getWaveDirectionOptions,
  getWaveDomainOptions,
  getWaveTypeOptions
} from "@/utils/appCommon/appCommonOptions/wave";
import { getIotDataOneWaveApi, getIotDataRealtimeWaveApi } from "@/api/iotdata/iotdata";
import { ElButton, ElMessage } from "element-plus";
import { getCommonMathWave } from "@/utils/appCommon/waveMath/waveCommon";
import { ProductKeyVI1, ProductKeyVI2 } from "@/consts/product";
import { getProductKeys } from "@/utils/appCommon/appCommonOptions/products";
import { getProductAttributes } from "@/utils/appCommon/appCommonOptions/deviceParam";
import { useI18n } from "vue-i18n";

// 定义组件事件
const emit = defineEmits(['prevPage', 'nextPage', 'onRemove']);
const {t} = useI18n()
const props = defineProps({
  productKey: { //产品key
    type: String,
    required: false,
    default: "",
  },
  deviceOptions: { //设备表单选项
    type: Array,
    required: false,
    default: [],
  },
  deviceNo:{   //默认选中的deviceNo
    type: String,
    required: false,
    default: "",
  },
  sampletime:{
    type: Number,
    required: false,
    default: 0,
  },
  isRealtime:{   //是不是获取实时数据
    type: Boolean,
    required: false,
    default: false,
  },
  index: {   // 序号代表第几个卡片
    type: Number,
    required: false
  },
  showParamsArea: {
    type: Boolean,
    default: false
  },
})
let refreshTimer: number | null = null;
const isAutoRefreshing = ref(false);
const refreshInterval = ref(5000);
let rdForViewUpdate = ref(0);
const xData = ref<number[]>([])
const yData = ref<number[]>([])
const xLabel = ref("")
const yLabel = ref("")
const aeWaveTitle = ref("")
const selectedDomainType = ref(0)
const isRealtime = ref(false) // 是不是要获取实时数据
const paramValues = ref<any[]>([])
const pageFlag = ref(0)

const form = reactive({
  productKey: props.productKey,  //产品键
  deviceNo: "",  //设备编号
  type:"ae",   //波形类型 ae  vi
  domain: 0,  // 0时域 1频域
  direction: 0, //方向 0x，1y，2z
  pageFlag:0,   //0当前页 1下一页 -1上一页
  sampletime: 0,  //采样时间
})
const showParamsArea = ref(props.showParamsArea)
const deviceOptions = ref(props.deviceOptions)
const waveTypeOptions = ref([])
const waveDomainOptions = ref([])
const waveDirectionOptions = ref([])
const renderFlag = ref(0)
onMounted(async ()=>{
  waveTypeOptions.value = await getWaveTypeOptions();
  waveDomainOptions.value= await getWaveDomainOptions()
  waveDirectionOptions.value= await getWaveDirectionOptions()
})
const productAttributes = computed(() => getProductAttributes(form.productKey))
watch(
  () => props,
  (newParams) => {
    pageFlag.value = 0
    form.productKey = newParams.productKey

    // 默认波形的显示类型
    if(form.productKey == ProductKeyVI1 || form.productKey==ProductKeyVI2){
      form.type = "vi"
    }else{
      form.type = "ae"
    }

    deviceOptions.value = newParams.deviceOptions
    form.deviceNo = newParams.deviceNo ? newParams.deviceNo : ""
    form.sampletime = newParams.sampletime ? newParams.sampletime : 0
    isRealtime.value = newParams.isRealtime ? newParams.isRealtime : false
    if (newParams.deviceNo) {
      setTimeout(async ()=>{
        await fetchWaveData()
      },10)
    }
  },
  { immediate: true,deep: true }
);
const onIsRealtimeChange =(e:boolean)=>{
  console.log(e)
  if (!e) {
    if (refreshTimer) {
      clearInterval(refreshTimer);
      refreshTimer = null
    }
    setTimeout(async () => {
      await fetchWaveData()
    },10)
  }
}
const onisAutoRefreshingChange = (e:boolean) => {
  console.log(e)
  if(!e) {
    if (refreshTimer) {
      clearInterval(refreshTimer);
      refreshTimer = null
    }
  }else{
    refreshTimer = window.setInterval(async () => {
      // 这里可以添加实际的数据刷新逻辑
      console.log(`数据刷新，间隔: ${refreshInterval.value}ms`);
      await fetchWaveData()
      // 触发视图更新
      rdForViewUpdate.value = Math.random();
    }, refreshInterval.value);
  }
}



// 上一页按钮点击事件
const handlePrevPage = async () => {
  if(isAutoRefreshing.value){
    ElMessage({
      type: 'warning',
      message: t('device.wavebox.cannotPageInRealtime')
    });
    return
  }
  pageFlag.value = -1
  await fetchWaveData()
};

// 下一页按钮点击事件
const handleNextPage =async () => {
  if(isAutoRefreshing.value){
    ElMessage({
      type: 'warning',
      message: t('device.wavebox.cannotPageInRealtime')
    });
    return
  }
  pageFlag.value = 1
  await fetchWaveData()
};
const loading = ref(false);
const fetchWaveData = async () => {
  if(loading.value || !form.deviceNo) {
    return;
  }
  if(!isRealtime.value && (!form.sampletime || form.sampletime==0)){
    return
  }
  form.domain = 0 //服务端只保存时域
  form.pageFlag = pageFlag.value
  const copyform = Object.assign({}, toRaw(form))
  const targetDomain = selectedDomainType.value
  loading.value = true;
  try {
    const {code, data } = isRealtime.value
      ? await getIotDataRealtimeWaveApi({
          deviceNo: form.deviceNo,
          type: form.type,
          domain: form.domain,
          direction: form.direction
        })
      : await getIotDataOneWaveApi({
          sampletime: form.sampletime,
          pageFlag: form.pageFlag,
          deviceNo: form.deviceNo,
          type: form.type,
          domain: form.domain,
          direction: form.direction
        });
    if (code == 0){
      // 处理返回的波形数据
        if(data.wave && data.wave.length > 0 && data.data && data.data.sampletime>0){
          let paraData = data.data
          if(data.data.data){
            paraData = data.data.data
          }
          const timestamp = paraData.sampletime
          const date = new Date(timestamp / 1000); // 微秒转毫秒
          const formattedDate = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}.${(timestamp % 1000000).toString().padStart(6, '0')}`;
          const waveData = data.wave
          const mathWaveRes = await getCommonMathWave(copyform.productKey,copyform.type,waveData,paraData,targetDomain)
          aeWaveTitle.value = copyform.deviceNo + " " +  formattedDate
          xLabel.value = mathWaveRes.xunit
          yLabel.value = mathWaveRes.yunit
          xData.value = mathWaveRes.xdata
          yData.value = mathWaveRes.ydata
          form.sampletime = timestamp
          // 将参数数据paraData 生成给paramValues
          if (paraData && productAttributes.value.length > 0) {
            paramValues.value = productAttributes.value.map(attr => {
              // 深拷贝原始属性对象
              const newAttr = { ...attr };
              // 检查paraData中是否有对应键名的属性
              if (paraData.hasOwnProperty(attr.val)) {
                newAttr.value = paraData[attr.val];
              }
              return newAttr;
            });
          } else {
            paramValues.value = [];
          }
        }else{
          xData.value = []
          yData.value = []
          paramValues.value = [];
        }
    }else{
      xData.value = []
      yData.value = []
    }
    renderFlag.value = Math.random()
    // 触发视图更新
    rdForViewUpdate.value = Math.random();
  } catch (error) {
    console.error('获取波形数据失败:', error);
    xData.value = []
    yData.value = []
    renderFlag.value = Math.random()
  }finally {
    loading.value = false;
  }
};



const settingsDialogVisible = ref(false);

const handleOnRemove = (index:number) => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null
  }
  emit("onRemove", index);
}

onUnmounted(()=>{
  handleOnRemove(props.index)
})

</script>

<template>
  <el-card class="data-card">
    <template #header>
      <div class="card-header">
        <span class="card-title"></span>
        <div class="card-actions">
          <el-button type="primary" size="small" @click="settingsDialogVisible = true">
            {{t('buttons.setting')}}
          </el-button>

          <el-button type="primary" size="small" @click="handlePrevPage">{{ t('device.wavebox.prevPage') }}</el-button>
          <el-button type="primary" size="small" @click="handleNextPage">{{ t('device.wavebox.nextPage') }}</el-button>
          <el-button size="small" type="warning" :icon="Delete" @click="handleOnRemove(props.index)"></el-button>
        </div>
      </div>
    </template>
    <div class="card-content">
      <Aewave
        :title="aeWaveTitle"
        :xAxisUnit="xLabel"
        :xAxisData="xData"
        :yAxisUnit="yLabel"
        :yAxisData="yData"
        :showParams="showParamsArea"
        :params="paramValues"
        :renderFlag="renderFlag"
      />
    </div>

    <el-dialog v-model="settingsDialogVisible" :title="t('device.wavebox.setting')" width="600px" :draggable="true">
      <el-form label-width="120px">

        <el-form-item :label="t('device.wavebox.deviceNo')">
          <el-select v-model="form.deviceNo" placeholder="设备编号" size="small" style="width: 100%">
            <el-option v-for="option in deviceOptions" :key="option.val" :label="option.label" :value="option.val" />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('device.wavebox.waveType')">
          <el-select v-model="form.type" placeholder="波形类型" size="small" style="width: 100%">
            <el-option v-for="option in waveTypeOptions" :key="option.val" :label="option.label" :value="option.val" />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('device.wavebox.domain')">
          <el-select v-model="selectedDomainType" placeholder="分析域" size="small" style="width: 100%">
            <el-option v-for="option in waveDomainOptions" :key="option.val" :label="option.label" :value="option.val" />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('device.wavebox.direction')" v-show="form.type=='vi'">
          <el-select v-model="form.direction" placeholder="方向" size="small" style="width: 100%">
            <el-option v-for="option in waveDirectionOptions" :key="option.val" :label="option.label" :value="option.val" />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('device.wavebox.realtime')">
          <el-switch v-model="isRealtime"  @change="onIsRealtimeChange" />
        </el-form-item>

        <el-form-item :label="t('device.wavebox.refreshInterval')">
          <el-select v-model="refreshInterval" placeholder="刷新间隔" size="small" style="width: 100%">
            <el-option :value="1000" label="1s" />
            <el-option :value="2000" label="2s" />
            <el-option :value="3000" label="3s" />
            <el-option :value="5000" label="5s" />
            <el-option :value="10000" label="10s" />
            <el-option :value="100" label="100ms" />
            <el-option :value="200" label="200ms" />
            <el-option :value="500" label="500ms" />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('device.wavebox.autoRefresh')">
          <el-switch v-model="isAutoRefreshing" @change="onisAutoRefreshingChange"/>
        </el-form-item>

        <el-form-item :label="t('device.wavebox.showParamsArea')">
          <el-switch v-model="showParamsArea"/>
        </el-form-item>
      </el-form>
    </el-dialog>

  </el-card>
</template>

<style scoped lang="scss">
.data-card {
  margin-bottom: 16px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    overflow-x: auto;

    .card-actions {
      display: flex;
      gap: 1px;
    }
  }
}
</style>
